/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.spi.determination.basetypes.nestedTrans;

import com.inspur.edp.cef.api.dataType.valueObj.ICefValueObject;
import com.inspur.edp.cef.api.determination.ICefDeterminationContext;
import com.inspur.edp.cef.api.determination.NestedTransmitType;
import com.inspur.edp.cef.api.manager.ICefValueObjManager;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import com.inspur.edp.cef.entity.changeset.Util;
import com.inspur.edp.cef.entity.entity.IValueObjData;
import com.inspur.edp.cef.spi.common.UdtManagerUtil;
import com.inspur.edp.cef.spi.determination.IDetermination;
import java.util.Objects;

public abstract class CefNestedTransDtmAdapter implements IDetermination {

  private final String name;
  protected final String propertyName;
  private final String udtConfig;
  private NestedTransmitType transType;

  public CefNestedTransDtmAdapter(String name,String propertyName,String udtConfig) {
    this(name, propertyName, udtConfig, NestedTransmitType.ValueChanged);
  }

  public CefNestedTransDtmAdapter(String name,String propertyName,String udtConfig, NestedTransmitType transType) {
    this.name = name;
    this.propertyName = propertyName;
    this.udtConfig = udtConfig;
    this.transType = transType;
  }

  @Override
  public String getName() {
    return name;
  }

  @Override
  public boolean canExecute(IChangeDetail change){
    switch (transType) {
      case ValueChanged:
        return Util.containsAny(change, new String[]{propertyName});
      case Always:
        return true;
      default:
        throw new IllegalArgumentException("错误的触发类型"+ transType);
    }
  }

  @Override
  public void execute(ICefDeterminationContext context, IChangeDetail change) {
    if (context.getData() == null)     return;
    IValueObjData data= (IValueObjData) context.getData().getValue(propertyName);
    if (data == null)     return;
    ICefValueObjManager valueObjMgr=(ICefValueObjManager) UdtManagerUtil.getUdtFactory().createManager(udtConfig);
    ICefValueObject valueObj=valueObjMgr.createValueObject(data);
    doExecute(valueObj, context, change);
  }

  protected abstract void doExecute(ICefValueObject valueObject,ICefDeterminationContext context,
      IChangeDetail change);
}
